package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.entity.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.pojo.dto.LikeRecordFormDTO;
import com.tianji.remark.service.ILikedRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author xjs
 */
//@Service
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    @Autowired
    private RabbitMqHelper mqHelper;

    @Override
    public List<String> listLikeRecords(List<Long> bizIds, String bizType) {
        Long userId = UserContext.getUser();//？？？？ feign调用能否拿到用户id？
        if(userId == null){
            return new ArrayList<>();
        }
        LambdaQueryWrapper<LikedRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LikedRecord::getUserId, userId)
                .eq(LikedRecord::getBizType, bizType)
                .in(LikedRecord::getBizId, bizIds);
        List<LikedRecord> list = this.list(queryWrapper);
        if(CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }
        return list.stream().map(l->String.valueOf(l.getBizId())).collect(Collectors.toList());
    }

    @Override
    public void likeOrUnlike(LikeRecordFormDTO dto) {
        // 获取用户
        Long userId = com.tianji.common.utils.UserContext.getUser();
        // 判断是否是点赞
        Boolean liked = dto.getLiked();
        if(liked){
            // 是
            //    是否点过赞，查库
            LambdaQueryWrapper<LikedRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LikedRecord::getUserId, userId)
                    .eq(LikedRecord::getBizId, dto.getBizId())
                    .eq(LikedRecord::getBizType, dto.getBizType());
            LikedRecord record = this.getOne(queryWrapper);
            if(record != null){
                //        是，不能重复点赞，结束
                return;
            }
            //        否，新增点赞记录
            LikedRecord likedRecord = com.tianji.common.utils.BeanUtils.copyBean(dto, LikedRecord.class);
            likedRecord.setUserId(userId);
            likedRecord.setCreateTime(LocalDateTime.now());
            likedRecord.setUpdateTime(LocalDateTime.now());
            this.save(likedRecord);
            //            统计最新的点赞数量
            queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LikedRecord::getBizId, dto.getBizId()).eq(LikedRecord::getBizType, dto.getBizType());
            int likedCount = this.count(queryWrapper);
            // 发送mq消息
            LikedTimesDTO msg = new LikedTimesDTO();
            msg.setBizId(dto.getBizId());
            msg.setLikedTimes(likedCount);

            String routingKey = StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, dto.getBizType());
            mqHelper.send(MqConstants.Exchange.LIKE_RECORD_EXCHANGE, routingKey, msg);
        }else{
            // 否
            //    判断是否点过赞
            //    是否点过赞，查库
            LambdaQueryWrapper<LikedRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LikedRecord::getUserId, userId)
                    .eq(LikedRecord::getBizId, dto.getBizId())
                    .eq(LikedRecord::getBizType, dto.getBizType());
            LikedRecord record = this.getOne(queryWrapper);
            if(record == null){
                //       否，结束
                return;
            }
            //       是
            //          删除点赞记录
            this.removeById(record.getId());
            //          统计最新的点赞数量
            queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LikedRecord::getBizId, dto.getBizId()).eq(LikedRecord::getBizType, dto.getBizType());
            int likedCount = this.count(queryWrapper);
            //发送mq消息
            LikedTimesDTO msg = new LikedTimesDTO();
            msg.setBizId(dto.getBizId());
            msg.setLikedTimes(likedCount);
            String routingKey = StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, dto.getBizType());
            mqHelper.send(MqConstants.Exchange.LIKE_RECORD_EXCHANGE, routingKey, msg);
        }
    }
}
